<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable placeholder="Id" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.description" :placeholder="$t('permission.roleKey')" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in roles" :key="item.roleKey" :label="item.name" :value="item.roleKey" />
      </el-select>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        {{ $t('common.export') }}
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="Id" width="50px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('permission.userId')" prop="id" align="center" width="180px">
        <template slot-scope="{row}">
          <span>{{ row.userId }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.name')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.email')" width="200px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('permission.roleKey')" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.roleKey }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.state')" prop="statusFlag" sortable="custom" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.statusFlag }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.introduction')" width="*" align="center">
        <template slot-scope="{row}">
          <span>{{ row.introduction }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="250px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.userId!='administrator' && row.statusFlag !='lock'" type="info" size="mini" @click="handUpdateState('lock',row,$index)">
            {{ $t('permission.lock') }}
          </el-button>
          <el-button v-if="row.userId!='administrator'&& row.statusFlag !='unlock'" type="success" size="mini" @click="handUpdateState('unlock',row,$index)">
            {{ $t('permission.unlock') }}
          </el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button v-if="row.userId!='administrator'" size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="150px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="temp.userId!='administrator'" :label="$t('permission.roleKey')" prop="roleKey">
          <el-select v-model="temp.roleKey" :placeholder="$t('permission.roleKey')">
            <el-option v-for="item in roles" :key="item.roleKey" :label="item.name" :value="item.roleKey" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="temp.userId!='administrator'" :label="$t('permission.userId')" prop="userId">
          <el-input v-model="temp.userId" />
        </el-form-item>
        <el-form-item :label="$t('common.name')">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item :label="$t('login.password')" prop="password">
          <el-input v-model="temp.password" type="password" :placeholder="$t('login.password')" />
        </el-form-item>
        <el-form-item :label="$t('login.password2')" prop="password2">
          <el-input v-model="password2" type="password" :placeholder="$t('login.password2')" />
        </el-form-item>
        <el-form-item :label="$t('common.email')">
          <el-input v-model="temp.email" type="email" />
        </el-form-item>
        <el-form-item :label="$t('common.introduction')">
          <el-input v-model="temp.introduction" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { fetchPv } from '@/api/article'
import { getRoles } from '@/api/role'
import { getUsers, updateUser, updateStatus, creatUser, deleteUser } from '@/api/user'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import i18n from '@/lang'

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (this.password2 === undefined) {
        callback(new Error(i18n.t('msg.CAN_NOT_BE_NULL')))
      } else if (this.password2 !== this.temp.password) {
        callback(new Error(i18n.t('msg.NOT_SAME')))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: [],
      roles: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        state: '',
        lineNumber: '',
        name: '',
        description: ''
      },
      showReviewer: false,
      temp: {
        id: 0,
        userId: '',
        roleKey: '',
        statusFlag: 'lock',
        name: '',
        password: '',
        email: '',
        introduction: ''
      },
      password2: '',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        userId: [{ required: true, message: i18n.t('msg.ACCOUNT_CAN_NOT_BE_NULL'), trigger: 'change' }],
        password: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        password2: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
    this.getType()
    this.listQuery.lineNumber = this.$store.getters.lineNumber
  },
  methods: {
    // 获取所有类型清单
    getType() {
      this.listLoading = true
      getRoles().then(response => {
        this.roles = response.data
        this.listLoading = false
      })
    },
    // 获取清单
    getList() {
      this.listLoading = true
      getUsers(this.listQuery).then(response => {
        this.list = response.data.users
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序时调用
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'statusFlag') {
        this.sortByStatus(order)
      }
    },
    // 根据状态排序
    sortByStatus(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+status_flag'
      } else {
        this.listQuery.sort = '-status_flag'
      }
      this.handleFilter()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        id: 0,
        userId: '',
        roleKey: '',
        statusFlag: 'lock',
        name: '',
        password: '',
        email: '',
        introduction: ''
      }
      this.password2 = ''
    },
    // 新建一个任务
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatUser(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 更改用户状态
    handUpdateState(state, row, index) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.statusFlag = state
      updateStatus(this.temp).then((response) => {
        this.$notify({
          title: i18n.t('common.tip'),
          message: i18n.t('msg.UPDATE_SUCCESS'),
          type: 'success',
          duration: 2000
        })
        this.temp.statusFlag = state
        this.list.splice(index, 1, this.temp)
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.password2 = this.temp.password
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_ACCOUNT_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.ok'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteUser(this.temp).then(() => {
            this.$notify({
              title: i18n.t('common.tip'),
              message: i18n.t('msg.DELETE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        })
        .catch(err => { console.error(err) })
    },
    handleFetchPv(pv) {
      fetchPv(pv).then(response => {
        this.pvData = response.data.pvData
        this.dialogPvVisible = true
      })
    },
    // 下载所有导出信息
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', '用户ID', '名字', '邮箱', '角色', '状态', '介绍']
        const filterVal = ['id', 'userId', 'name', 'email', 'roleKey',
          'statusFlag', 'introduction']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '用户信息'
        })
        this.downloadLoading = false
      })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
    // getSortClass: function(key) {
    //   const sort = this.listQuery.sort
    //   return sort === `+${key}` ? 'ascending' : 'descending'
    // }
  }
}
</script>
